<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>原料入库编辑</title>
    {% include 'system/common/header.html' %}
</head>
<body>
<form class="layui-form" action="" lay-filter="myForm">
    <div class="mainBox">
        <div class="main-container">
            <div class="main-container">
                <div class="layui-card-body">
                    <div class="layui-tab layui-tab-brief">
                         <ul class="layui-tab-title">
                        <li class="layui-this" id="tab_li_1">入库信息</li>
                             <li>其他信息</li>

                              <li id="tab_li_5" >资质信息</li>
                        </ul>
                        <div class="layui-tab-content">
                            <div class="layui-tab-item layui-show">
                            <div class="layui-form-item layui-hide">
                                    <label class="layui-form-label">编号</label>
                                    <div class="layui-input-block">
                                        <input type="text" value="{{ info.id }}" name="id" lay-verify="title"
                                               autocomplete="off" placeholder="请输入标题" class="layui-input" >
                                    </div>
                                </div>
                               <div class="layui-form-item">
                                    <label class="layui-form-label">品名</label>
                                    <div class="layui-input-block">
                                            <select  lay-verify="required" name="raw_id" lay-search="" lay-filter="select-filter-pm" id="select-pm" >
                                              <option value="{{ raw_info.id }}">{{ raw_info.品名 }}</option>
                                                {% for good in goods %}
                                                     <option value="{{ good.id }}">{{ good.品名 }}</option>
                                                {% endfor %}

                                            </select>
                                    </div>
                                </div>

                                <div class="layui-form-item">
                                    <label class="layui-form-label">供应商名</label>
                                    <div class="layui-input-block">
                                       <select lay-verify="required" name="supplier_id" lay-filter="select-filter-gys" id="select-gys" >
                                              <option value="{{ suplier.id  }}">{{ suplier.供应商名 }}</option>

                                       </select>


                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">规格</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="规格" lay-verify="required" autocomplete="off" placeholder="请输入内容"
                                               class="layui-input" id="规格" value="{{ info.规格 }}">
                                    </div>
                                </div>

                                <div class="layui-form-item">
                                    <label class="layui-form-label">产地</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="产地" lay-verify="required" autocomplete="off" placeholder="请输入内容"
                                               class="layui-input" id="产地" value="{{ info.产地 }}">
                                    </div>
                                </div>

                                <div class="layui-form-item">
                                    <label class="layui-form-label">批号</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="批号" lay-verify="required" autocomplete="off" placeholder="请输入内容"
                                               class="layui-input" id="批号" value="{{ info.批号 }}">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">代码</label>
                                    <div class="layui-input-block">
                                        <input type="text" readonly lay-verify="required" autocomplete="off" placeholder="请输入内容"
                                               class="layui-input" id="代码" value="{{ raw_info.代码 }}">
                                    </div>
                                </div>

                                <div class="layui-form-item">
                                    <label class="layui-form-label">数量</label>
                                    <div class="layui-input-block">
                                        <input type="number" lay-affix="number" step="0.001" lay-verify="required|number" name="store_number"  autocomplete="off" placeholder="请输入内容"
                                               class="layui-input" value="{{ info.store_number }}">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">单位</label>
                                    <div class="layui-input-block">
                                         <select lay-verify="required"  name="unit_id" lay-filter="select-filter-dw" id="select-dw" >
                                              <option value="">请选择</option>

                                       </select>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">单价</label>
                                    <div class="layui-input-block">
                                        <input type="number" name="price" lay-affix="number" value="{{ info.price }}"  lay-verify="required|number"  placeholder="设置小数位精度为 2" step="0.01"  class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">单据日期</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="date_time" lay-verify="required|date"  autocomplete="off" placeholder="yyyy-MM-dd"
                               class="layui-input"  id="ID-laydate-demo" value="{{ info.date_time }}" >
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">入库仓库</label>
                                    <div class="layui-input-block">
                                        <select lay-verify="required" disabled name="location_id" lay-search=""  lay-filter="select-filter-hw" id="select-hv" >
                                              <option value="">请选择</option>

                                       </select>
                                    </div>
                                </div>

                                <div class="layui-form-item">
                                    <label class="layui-form-label">备注</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="remark"  autocomplete="off" placeholder="请输入内容"
                                               class="layui-input" value="{% if info.remark %}{{ info.remark }}{% endif %}  ">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-tab-item">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">执行标准</label>
                                    <div class="layui-input-block">
                                        <input type="text" readonly  autocomplete="off" placeholder="请输入内容"
                                            id="执行标准"   value="{{ raw_info.执行标准 }}" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">药典贮存条件</label>
                                    <div class="layui-input-block">
                                        <input type="text" readonly autocomplete="off" placeholder="请输入内容"
                                            id="药典贮存条件" value="{% if raw_info.药典贮存条件 %}{{ raw_info.药典贮存条件 }}{% endif %}"  class="layui-input">
                                    </div>
                                </div>



                                <div class="layui-form-item">
                                    <label class="layui-form-label">养护内容</label>
                                    <div class="layui-input-block">
                                        <input type="text" readonly autocomplete="off" placeholder="请输入内容"
                                               class="layui-input" value="{% if raw_info.养护内容 %}{{ raw_info.养护内容 }}{% endif %}" id="养护内容">
                                    </div>
                                </div>
                            {% if authorize("user:power:raw:yp:keeper") %}
                                <div class="layui-form-item">
                                    <label class="layui-form-label">库管员</label>
                                    <div class="layui-input-block">
                                       <select lay-verify="required" name="user_keeper_id" lay-filter="select-filter-user-keeper" id="select-keeper" >
                                              <option value="{{ user_keeper.id }}">{{ user_keeper.realname }}</option>

                                       </select>


                                    </div>
                                </div>
                            {% endif %}
                                {% if authorize("user:power:raw:yp:buyer") %}
                                <div class="layui-form-item">
                                    <label class="layui-form-label">采购人员</label>
                                    <div class="layui-input-block">
                                       <select  name="user_buyer_id" lay-filter="select-filter-user-buyer" id="select-buyer" >
                                           {% if user_buyer %}
                                               <option value="{{ user_buyer.id }}">{{ user_buyer.realname }}</option>
                                           {% else %}
                                                <option value="">请选择</option>
                                            {% endif %}
                                       </select>


                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">采购日期</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="buyer_time" lay-verify="date"  autocomplete="off" placeholder="yyyy-MM-dd"
                               class="layui-input"  id="ID-laydate" value="{% if info.buyer_time %}{{ info.buyer_time }}{% endif %}">
                                    </div>
                                </div>
                                {% endif %}
                            {% if authorize("user:power:raw:yp:qa") %}
                                <div class="layui-form-item">
                                    <label class="layui-form-label">验收员</label>
                                    <div class="layui-input-block">
                                       <select  name="user_qa_id" lay-filter="select-filter-user-qa" id="select-qa" >
                                               {% if user_qa %}
                                               <option value="{{ user_qa.id }}">{{ user_qa.realname }}</option>
                                           {% else %}
                                                <option value="">请选择</option>
                                            {% endif %}

                                       </select>


                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">验收日期</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="qa_time" lay-verify="date"  autocomplete="off" placeholder="yyyy-MM-dd"
                               class="layui-input"  id="ID-laydate" value="{% if info.qa_time %}{{ info.qa_time }}{% endif %}">
                                    </div>
                                </div>
                            </div>
                             {% endif %}
                            <div class="layui-tab-item" id="tab_files">
                               <div class="layui-upload">
                                      <button type="button" class="layui-btn layui-btn-normal" id="ID-upload-files">选择多文件</button>

                                      <div class="layui-upload-list">

                                        <table class="layui-table" id="uplord-table">

                                          <colgroup>

                                            <col style="min-width: 100px;" >

                                            <col width="150">


                                            <col width="260">

                                            <col width="150">

                                          </colgroup>

                                          <thead>

                                            <th>文件名</th>

                                            <th>大小</th>


                                            <th>上传进度</th>

                                            <th>操作</th>

                                          </thead>

                                          <tbody id="ID-upload-files-list"></tbody>

                                        </table>

                                      </div>
                            </div>
                                <hr class="layui-border-green">
                                <span class="title">已上传附件信息</span>
                                <div class="layui-card-body">
                                <table id="file-table" lay-filter="file-table"></table>

                                </div>
                        </div>
                   </div>
                   </div>
                </div>





            </div>
        </div>
    </div>
    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="pear-btn pear-btn-primary pear-btn-sm" lay-submit=""
                    lay-filter="user-update" id="user-save">
                <i class="layui-icon layui-icon-ok"></i>
                提交
            </button>
            <button type="reset" class="pear-btn pear-btn-sm">
                <i class="layui-icon layui-icon-refresh"></i>
                重置
            </button>
        </div>
    </div>
</form>

{% raw %}

<script type="text/html" id="dict-type-enable">
    <input type="checkbox" value="{{ d.id }}" lay-skin="switch" lay-text="在用|停用" lay-filter="dict-type-enable"
            {{ "{{# if(d.状态==1){ }} checked {{# } }}" }}>

</script>
<script type="text/html" id="user-createTime">
    {{layui.util.toDateString(d.有效期至,  "yyyy-MM-dd")}}
</script>

<script type="text/html" id="file-bar">

    <button type="button" class="pear-btn pear-btn-danger pear-btn-sm" lay-event="remove"><i class="layui-icon layui-icon-delete"></i>
    </button>
    <button type="button" class="pear-btn pear-btn-warming pear-btn-sm" lay-event="downlord">

        <i class="layui-icon layui-icon-download-circle"></i>
    </button>
</script>

{% endraw %}
{% include 'system/common/footer.html' %}
<script>
    layui.use(['form', 'jquery', 'dtree', 'table'], function () {
        let form = layui.form
        let $ = layui.jquery
        let dtree = layui.dtree
        var laydate = layui.laydate;
         var transfer = layui.transfer;
          var upload = layui.upload;
            var element = layui.element;
            var table = layui.table;
            var layer = layui.layer;

            var lordfiles=[]
             // 获取当前日期
               window.getCurrentDate=function() {
                    const date = new Date();
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
                    const day = String(date.getDate()).padStart(2, '0');
                    return year+'-'+month+'-'+day;
                };
                window.getPH=function() {
                    var currentdate = $("#ID-laydate-demo").val(); // 获取选中的值
                    var id = $("#select-pm").val(); // 获取选中的值

                    //获取最新批号
                    $.ajax({
                            url: '/api/store/PHYPyl',
                            data:JSON.stringify({
                                current_date:currentdate,
                                id:id
                            }),
                            dataType: 'json',
                            contentType: 'application/json',
                            type: 'post',
                            success: function (result) {

                              if (result.success) {

                                $('#批号').val(result.批号)
                              } else {
                                  $('#批号').val(result.批号)
                                layer.msg(result.msg, { icon: 2, time: 5000 })


                              }
                            }
                          });
                };

              // 渲染
             laydate.render({
                elem: '#ID-laydate-demo',
                 done: function(value, date, endDate){
                         window.getPH()
                }
              });
             laydate.render({
                elem: '#ID-laydate',
              });

        //获取物料重量单位
        $.ajax({
                url: '/api/dict/unitYPyl',
                data:JSON.stringify({
                         id:'{{ info.unit_id }}'
                        }),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {

                  if (result.success) {

                     $('#select-dw option[value !=""]').remove();
                    result.data.forEach(function(unit) {
                      // 创建新的 option 元素
                      var newOption = $('<option>', {
                        value: unit.id, // 设置 value 属性
                        text: unit.data_label // 设置显示文本
                      });
                      $("#select-dw").append(newOption);
                      $("#select-dw").val("{{ info.unit_id }}")
                    });
                    form.render('select')
                  } else {
                    layer.msg(result.msg, { icon: 2, time: 5000 })


                  }
                }
              });
    //获取货位
    $.ajax({
                url: '/api/store/HVYPyl',
                data:JSON.stringify({id:'{{ location.id }}'}),
                dataType: 'json',
                contentType: 'application/json',
                type: 'post',
                success: function (result) {

                  if (result.success) {

                     $('#select-hv option[value !=""]').remove();
                    result.data.forEach(function(unit) {
                        var tex_type=unit.type==0 ? '仓库' :unit.type==1 ? '库区' : '货位'
                      // 创建新的 option 元素
                      var newOption = $('<option>', {
                        value: unit.id, // 设置 value 属性
                        text: tex_type +'|'+unit.hv_text // 设置显示文本
                      });
                      $("#select-hv").append(newOption);
                      $("#select-hv").val('{{ location.id }}')
                    });
                    form.render('select')
                  } else {
                    layer.msg(result.msg, { icon: 2, time: 5000 })


                  }
                }
              });
    //获取采购人员、库管员、QA
    $.ajax({
                url: '/api/store/userYPyl',
                dataType: 'json',
                contentType: 'application/json',
                type: 'get',
                success: function (result) {

                  if (result.success) {

                     $('#select-keeper option[value !=""]').remove();
                    $('#select-qa option[value !=""]').remove();
                    $('#select-buyer option[value !=""]').remove();
                    result.keeper.forEach(function(unit) {

                      // 创建新的 option 元素
                      var newOption = $('<option>', {
                        value: unit.id, // 设置 value 属性
                        text: unit.realname  // 设置显示文本
                      });
                      $("#select-keeper").append(newOption);
                    });
                    result.buyer.forEach(function(unit) {

                      // 创建新的 option 元素
                      var newOption = $('<option>', {
                        value: unit.id, // 设置 value 属性
                        text: unit.realname  // 设置显示文本
                      });
                      $("#select-buyer").append(newOption);
                    });
                    result.qa.forEach(function(unit) {

                      // 创建新的 option 元素
                      var newOption = $('<option>', {
                        value: unit.id, // 设置 value 属性
                        text: unit.realname  // 设置显示文本
                      });
                      $("#select-qa").append(newOption);
                    });
                    form.render('select')
                  } else {
                    layer.msg(result.msg, { icon: 2, time: 5000 })


                  }
                }
              });

    // select 事件

      form.on('select(select-filter-pm)', function(data){
        var elem = data.elem; // 获得 select 原始 DOM 对象
        var value = data.value; // 获得被选中的值
        var othis = data.othis; // 获得 select 元素被替换后的 jQuery 对象
        $.ajax({
                url: '/store/raw/yp/raw/'+value,

                dataType: 'json',
                contentType: 'application/json',
                type: 'get',
                success: function (result) {

                  if (result.success) {
                    window.rawdata(true,result)
                    window.getPH()
                  } else {

                      window.rawdata(false,result)

                  }
                }
              });
      });
            // 表格数据
        let cols = [
            [

                {title: '文件名', field: '文件名', align: 'center', width: 360},
                {title: '大小', field: '大小', align: 'center' , width: 100},


                {title: '操作', toolbar: '#file-bar', align: 'center', width: 180}
            ]
        ]

        // 渲染表格数据
        table.render({
            elem: '#file-table',
            id:'file-table',
            url: '/store/raw/yp/file/data',
            method:'get',
            where:{id:'{{ info.id }}'},
            page: false,
            cols: cols,
            skin: 'line',
            title:'dhi',
            height: 'full-148',
            toolbar: '#user-toolbar', /*工具栏*/
            text: {none: '暂无附件信息'},
             defaultToolbar: [{layEvent: 'refresh', icon: 'layui-icon-refresh'}, 'filter', 'print', 'exports'] /*默认工具栏*/
        })


        window.removeData = function (obj) {
          layer.confirm('确定要删除该字典值', { icon: 3, title: '提示' }, function (index) {
            layer.close(index)
            let loading = layer.load()
            $.ajax({
              url: '/store/raw/yp/file/remove/' + obj.data['id'],
              dataType: 'json',
              type: 'delete',
              success: function (result) {
                layer.close(loading)
                  table.reload('file-table')
                if (result.success) {
                  popup.success(result.msg, function () {
                    obj.del()

                  })

                } else {
                  popup.failure(result.msg)
                }
              }
            })
          })
        }
        window.downlordData = function (obj) {

          window.location.href = '/_uploads/storeRawYp/'+obj.data['文件名']

    }
        window.refresh = function (param) {
            table.reload('file-table', {where: param})
        }
        table.on('tool(file-table)', function (obj) {
          if (obj.event === 'remove') {
            window.removeData(obj)
          }  else if (obj.event === 'downlord') {
            window.downlordData(obj)
          }
        })
        table.on('toolbar(file-table)', function (obj) {
            if (obj.event === 'add') {
                window.add()
            } else if (obj.event === 'refresh') {
                window.refresh()
            } else if (obj.event === 'batchRemove') {
                window.batchRemove(obj)
            }
        })

        form.on('submit(user-update)', function (data) {
            var rowCount = $('#uplord-table tbody tr').length;
            if (rowCount === 0) {

                $.ajax({
                url: '/store/raw/yp/update',
                data: JSON.stringify(data.field),
                dataType: 'json',
                contentType: 'application/json',
                type: 'put',
                success: function (result) {
                    if (result.success) {
                        layer.msg(result.msg, {icon: 1, time: 1000}, function () {
                            parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
                            parent.layui.table.reload('user-table')
                        })
                    } else {
                        layer.msg(result.msg, {icon: 2, time: 6000})
                    }
                }
            })
            }

            return false
        })

        // 制作多文件上传表格

        var uploadListIns = upload.render({
            elem: '#ID-upload-files',
            elemList: $('#ID-upload-files-list'), // 列表元素对象
            url: "{{ url_for('store.raw.upload_api') }}", // 实际使用时改成您自己的上传接口即可。

            accept: 'file',
            multiple: true,
            unified:true,//多文件只请求一次
            number: 3,//最大上传量
            auto: false,
            bindAction: '#user-save',
            choose: function(obj){

              var that = this;
              var files = this.files = obj.pushFile(); // 将每次选择的文件追加到文件队列

              // 读取本地文件
              obj.preview(function(index, file, result){
                var tr = $(['<tr id="upload-'+ index +'">',
                  '<td>'+ file.name +'</td>',
                  '<td>'+ (file.size/1024).toFixed(1) +'kb</td>',

                  '<td><div class="layui-progress" lay-filter="progress-demo-'+ index +'"><div class="layui-progress-bar" lay-percent=""></div></div></td>',
                  '<td>',
                    '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>',
                    '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>',

                  '</td>',
                '</tr>'].join(''));


                // 单个重传
                tr.find('.demo-reload').on('click', function(){
                  obj.upload(index, file);
                });

                // 删除
                tr.find('.demo-delete').on('click', function(){
                  delete files[index]; // 删除对应的文件
                  tr.remove(); // 删除表格行

                  // 清空 input file 值，以免删除后出现同名文件不可选
                  uploadListIns.config.elem.next()[0].value = '';
                });



                that.elemList.append(tr);
                element.render('progress'); // 渲染新加的进度条组件



              });

            },

            done: function(res, index, upload){ // 成功的回调
                alert(JSON.stringify(res))
                {#alert(JSON.stringify(index))#}
                {#alert(JSON.stringify(upload))#}

              var that = this;
              // if(res.code == 0){ // 上传成功
                var tr = that.elemList.find('tr#upload-'+ index)
                var tds = tr.children();
                tds.eq(3).html(''); // 清空操作
                tds.eq(0).html(res.data.filename)
                lordfiles.push(Object.assign(res))
                delete this.files[index]; // 删除文件队列已经上传成功的文件
                return;

              //}

              this.error(index, upload);
            },

            allDone: function(obj){ // 多文件上传完毕后的状态回调



                console.log(JSON.stringify(lordfiles))
                // 获取表单其他数据
                  var formData = form.val('myForm');
                    {#alert(JSON.stringify(formData))#}



                    // 将文件上传结果和表单数据合并
                  var allData = Object.assign({}, formData, {fileInfo: lordfiles});
                  $.ajax({
                    url: '/store/raw/yp/update',
                    data: JSON.stringify(allData),
                    dataType: 'json',
                    contentType: 'application/json',
                    type: 'put',
                    success: function (result) {
                      if (result.success) {
                        layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
                          parent.layer.close(parent.layer.getFrameIndex(window.name))//关闭当前页
                          parent.layui.table.reload('user-table')
                        })
                      } else {
                        layer.msg(result.msg, { icon: 2, time: 5000 })
                      }
                    }
                  })
                  return false
            },
            before: function(obj){ // obj 参数同 choose
                {#return true#}

                // 获取表单其他数据
                var isValid = form.validate('.layui-input');  // 主动触发验证，v2.7.0 新增

                // 验证通过
                if(isValid) {
                    return true
                }else{

                    return false
                }
            },
            error: function(index, upload){ // 错误回调
              var that = this;
              var tr = that.elemList.find('tr#upload-'+ index);
              var tds = tr.children();
               // 显示重传
              tds.eq(5).find('.demo-reload').removeClass('layui-hide');

            },

            progress: function(n, elem, e, index){ // 注意：index 参数为 layui 2.6.6 新增
              element.progress('progress-demo-'+ index, n + '%'); // 执行进度条。n 即为返回的进度百分比
            }

  });

        window.rawdata=function (bool,result) {
        if(bool){
            $('#规格').val(result.raw.默认规格)
            $('#产地').val(result.raw.默认产地)
            $('#代码').val(result.raw.代码)
            $('#执行标准').val(result.raw.执行标准)
            $('#药典贮存条件').val(result.raw.药典贮存条件)
            $('#养护内容').val(result.raw.养护内容)
            $('#select-gys option[value !=""]').remove();
            result.suppliers.forEach(function(supplier) {
              // 创建新的 option 元素
              var newOption = $('<option>', {
                value: supplier.id, // 设置 value 属性
                text: supplier.供应商名 // 设置显示文本
              });
              $("#select-gys").append(newOption);
            });
        }else{
            layer.msg(result.msg, { icon: 2, time: 5000 })
            $('#规格').val('')
            $('#产地').val('')
            $('#批号').val('')
            $('#代码').val('')
            $('#执行标准').val('')
            $('#药典贮存条件').val('')
            $('#养护内容').val('')
            $('#select-gys option[value !=""]').remove();


        }


        // 重新渲染 select
        form.render('select');
        form.render('input')

    }
    })
</script>
</body>
</html>